package com.ip.common.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ip.common.constant.ZTConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.Inet4Address;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Component
@Slf4j
public class StartInit implements CommandLineRunner {
    @Autowired
    private RestTemplate restTemplate;

    @Resource
    Environment environment;

    @Value("${server.port}")
    private int port;

//    @Value("${server.localIp}")
//    private String localIp;

    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    public void run(String... args) throws Exception {
        register();
        //heartBeat();
        heartBeatTest();
    }
    public void register(){
        log.info("注册到Nacos开始进行中.......................start...................................");
        String res = cn.hutool.http.HttpRequest.post(ZTConstant.ZT_CONFIG_INSTANCE_PATH + this.getBaseRegistryArgs())
                .execute()
                .body();
        log.info("register heart body :{}", res);
        log.info("注册到Nacos结束.............................end.............................");
    }

    public void heartBeat(){
        new Thread(() -> {
            while (true) {
                Date st = DateUtil.date();
                log.info("------------------------发送心跳---------------------------");
                startHeartBeat();
                Date et = DateUtil.date();
                log.info("心跳请求耗时：{}s", DateUtil.between(st, et, DateUnit.SECOND));
                try {
                    // 心跳10s发送一次
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public void heartBeatTest(){
        new Thread(() -> {
            while (true) {
                Date st = DateUtil.date();
                log.info("------------------------new-start---------------------------");
                httpPutMethod();
                Date et = DateUtil.date();
                log.info("new心跳请求耗时：{}s", DateUtil.between(st, et, DateUnit.SECOND));
                try {
                    // 心跳10s发送一次
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 每6秒发送心跳到注册中心，
     */
    public void startHeartBeat()  {
        HttpHeaders headers = getHttpHeaders();
        Map<String, Object> params = new HashMap<>();
        HttpEntity reqParam = new HttpEntity(params, (MultiValueMap)headers);

        log.info("Nacos心跳开始..........................................................");
//        String res = cn.hutool.http.HttpRequest.put(ZTConstant.ZT_CONFIG_BEAT_PATH + this.getBaseRegistryArgs())
//                .execute()
//                .body();

        this.restTemplate.exchange(ZTConstant.ZT_CONFIG_BEAT_PATH + this.getBaseRegistryArgs(), HttpMethod.PUT, reqParam, String.class, new Object[0]);
        log.info("Nacos心跳结束..........................................................end");
//        JSONObject json = JSONObject.parseObject(res);
//        if(!"10200".equals(json.getString("code"))){
//            register();
//        }
    }


    /**
     * 测试每6秒发送心跳到注册中心，
     */
    public void startHeartBeatTest()  {
        HttpHeaders headers = getHttpHeaders();
        Map<String, Object> params = new HashMap<>();
        HttpEntity reqParam = new HttpEntity(params, (MultiValueMap)headers);

        log.info("测试百度心跳开始..........................................................");
        this.restTemplate.exchange("http://api-iop.jd.com/api/product/getCategory" + this.getBaseRegistryArgs(), HttpMethod.POST, reqParam, String.class, new Object[0]);
        log.info("测试百度心跳结束..........................................................end");
    }

    private void httpPutMethod(){
        // 创建HTTP客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        log.info("1..........................................................");
        // 构建PUT请求URL
        String putUrl = "http://api-iop.jd.com/api/product/getCategory"+this.getRegistryArgs(); // 替换为实际的上传URL
        log.info("2..........................................................");
        // 创建HTTP PUT请求
        HttpPut httpPut = new HttpPut(putUrl);
        log.info("3..........................................................");
        // 执行PUT请求并获取响应
        try{
            log.info("start..........................................................Nacos");
            HttpResponse response = httpClient.execute(httpPut);
            log.info("end............................................................Nacos");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static HttpHeaders getHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return headers;
    }

    private String getBaseRegistryArgs() {
        try{
            return "?ip=" + Inet4Address.getLocalHost().getHostAddress() + "&port=" + environment.getProperty("server.port") +
                    "&healthy=true&weight=1.0&serviceName=" + environment.getProperty("spring.application.name");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private String getRegistryArgs() {
        try{
            return "?ip=10.254.66.119" + "&port=" + port +
                    "&healthy=true&weight=1.0&serviceName=" + applicationName;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
